<template>
    <div class="article-list-container">
      <!-- 资讯列表 -->
      <!-- <div class="publish-btn" @click="handleAdd">
          <el-icon><EditPen /></el-icon>
          <div>发布</div>
      </div> -->
      <div class="search-div">
        <el-button type="info"  icon="Edit" @click="handleAdd()" style="background-color:#2a5caa;">上传活动</el-button>
        <!-- <el-button type="info"  icon="Document" @click="toMyOrder()" style="background-color:#c63c26;">我的帖子</el-button> -->
      </div>
      <el-card class="article-list-card">
        <!-- <h1 class="list-title">京剧活动</h1> -->
        <div class="article-list">
          <div
            v-for="article in articles"
            :key="article.id"
            class="article-item"
            @click="toDetailPage(article.id)"
          >
            <!-- 缩略图 -->
            <el-image
              :src="article.mainPic"
              class="article-thumbnail"
              fit="cover"
            ></el-image>
  
            <!-- 标题和发布时间 -->
            <div class="article-info">
              <h2 class="article-title">{{ article.title }}</h2>
              <div class="atl-tag">
                <el-tag type="primary">{{article.tags}}</el-tag>
              </div>
              <div class="article-meta">
                <span class="publish-date">活动时间： <strong class="green">{{ timestampToDayHM(article.activityDate) }}</strong></span>
              </div>
              <div class="atl-like">
                <!-- <span>{{article.likes}} 赞</span> -->
                <span>{{article.favs}} 人已报名</span>
              </div>
            </div>
          </div>
          <!-- 分页组件 -->
        <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getInfo" />
        </div>
      </el-card>
      <!-- 添加或修改对话框 -->
      <el-dialog v-model="open" title="上传活动" width="800px" append-to-body>
        <el-form label-width="130px" :model="editForm" :rules="rules" ref="formRef">
          <el-form-item label="活动标题" prop="title">
            <el-input
              v-model="editForm.title"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-input
              v-model="editForm.tags"
              auto-complete="off"
              placeholder='如：直播、线下活动'
            ></el-input>
          </el-form-item>
          <el-form-item label="活动时间" prop="activityDate">
            <el-date-picker
              v-model="editForm.activityDate"
              type="datetime"
              placeholder="选择日期与时间"
            />
          </el-form-item>
          <el-form-item label="正文内容" prop="content" id='quillEditorQiniu'>
            <el-input
              v-model="editForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入活动正文内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="题图" prop="role">
            <el-upload 
              class="avatar-uploader showUploader"
              ref="businessLicense"
              action
              :auto-upload="false"
              :show-file-list="false"
              :on-remove="handleRemoveLogo"
              :on-change="uploadLogoFile"
            >
            <ul class="img-list">
              <li v-if="editForm.mainPic==''" class="addpic"><el-icon><Plus/></el-icon></li>
            </ul>
            </el-upload>
            <ul class="img-list" v-if="editForm.mainPic!=''">
              <li class="img-li">
                <img :src="editForm.mainPic" class="avatar aspect-fill" style="width: 250px;height: 180px;" />
                <i class="logo-remove el-icon-delete" @click="handleRemoveLogo"><el-icon><Delete /></el-icon></i>
              </li>
            </ul>
          </el-form-item>

          <el-form-item label="附加图片" prop="role">
            <el-upload 
              class="avatar-uploader showUploader"
              ref="businessLicense"
              action
              multiple
              :auto-upload="false"
              :show-file-list="false"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="uploadSectionFile"
              :limit="6"
            >
              <ul class="img-list">
                <li v-for="(pic,i) in pics" :key="i" class="img-li" onclick="(function(e){e.stopPropagation()}(event))">
                  <img :src="pic" class="avatar aspect-fill" style="width: 250px;height: 180px;"/>
                  <i class="logo-remove el-icon-delete" @click="handleRemovePics(i)" ><el-icon><Delete /></el-icon></i>
                </li>
                <li v-if="pics.length==0 || pics.length<6" class="addpic avatar-uploader-icon"><el-icon><Plus /></el-icon></li>
              </ul>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
<script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
  
  const router = useRouter();
  const route = useRoute();
  // 查询参数
  const queryForm = reactive({
    deptName: "",
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);

  // 资讯数据
  const articles = ref<any>([]);

  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const openDetail = ref(false);
  //多图上传的返回图片url数组
  const pics = ref<any>([])
  const uploadUrlPath = ref();

  // 跳转到资讯详情页面
  const toDetailPage = (pid: number)=>{
    router.push("/activity/detail?nid="+pid);
  }

  // 提交表单数据
  let editForm = toRef(
    reactive({
      id: '',
      title: '',
      pics: '',
      mainPic: '',
      tags: '',
      activityDate: '',
      content: '',
      likes: 0,
      favs: 0,
      status: 0
    })
  );

  // 表单验证
  const rules = ref({
    title: [{ required: true, message: "请输入", trigger: "blur" }],
    tags: [{ required: true, message: "请输入", trigger: "blur" }],
    activityDate: [{ required: true, message: "请输入", trigger: "blur" }],
    content: [{ required: true, message: "请输入", trigger: "blur" }],
  });

  /**
   * 表单重置
   */
  function reset() {
    editForm.value = {
      id: '',
      title: '',
      pics: '',
      mainPic: '',
      tags: '',
      content: '',
      activityDate: '',
      likes: 0,
      favs: 0,
      status: 0
    };
    pics.value = []

    nextTick(() => {
      formRef.value?.resetFields();
    });
  }

  /**
 * 新增按钮操作
 */
  function handleAdd() {
    reset();
    open.value = true;
    console.log('图片:',pics.value)
  }

  const getInfo = () => {
    const cid = route.query.cid
    console.log('从路由获取参数：', route.query)
    let req = {category: cid}
    baseService.post(`/api/activity/list`, req).then((res) => {
      console.log('获取产品列表：',res)
      articles.value = res.data.records;
      total.value = res.data.totalrecord;
      loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
  }

  function handlePreview(file: any) {
    console.log(file);
}
function handleRemove(file: any, fileList: any) {
  alert('移除')
    //return this.$confirm(`确定移除 ${file.name}？`);
}
function beforeRemove(file: any, fileList: any) {
  alert('移除')
    // return this.$confirm(`确定移除 ${file.name}？`);
}

  // 图片上传
function uploadSectionFile(file: any) {
  console.log('选定图片！',file)
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    // ElMessage.error("只能是图片!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  if (!isLt3M) {
    // ElMessage.error("上传图片大小不能超过 3MB!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  // FormData 对象
  var formData = new FormData();
  // 文件对象
  formData.append("myFile", file.raw)
  console.log('上传图片表单：', formData)
  fileUploader(formData).then((res) => {
    if (res.data.errno==0) {
      //this.photoObj = res.data.data.objectId;
      console.log('图片上传成功！', res.data)
      pics.value.push(res.data.data);
    } else {
      // ElMessage.error(res.data.message);
    }
  })
}
  // 上传LOGO图片
function uploadLogoFile(file: any){
  const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
  const isJPG = typeArr.indexOf(file.raw.type) !== -1;
  const isLt3M = file.size / 1024 / 1024 < 3;
  if (!isJPG) {
    // ElMessage.error("只能是图片!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  if (!isLt3M) {
    // ElMessage.error("上传图片大小不能超过 3MB!");
    // this.$refs.upload.clearFiles();
    // this.files = null;
    return;
  }
  var formData = new FormData();
  formData.append("myFile", file.raw)
  fileUploader(formData).then((res) => {
    console.log('LOGO上传成功', res)
    if (res.data.errno==0) {
      editForm.value.mainPic=res.data.data[0]
    } else {
      // ElMessage.error(res.data.message);
    }
  })
}
// 移除LOGO图片
function handleRemoveLogo(file: any){
  editForm.value.mainPic=''
  console.log('移除LOGO图片！',editForm.value.mainPic)
}

// 移除多图中的其中一张
function handleRemovePics(idx: number){
  console.log('移除图片下标为：', idx)
  pics.value.splice(idx, 1);
}

/**
 * 提交按钮
 */
 function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    console.log('图片字段', pics.value)
    editForm.value.pics = pics.value.join(',')
    baseService.post(`/api/activity/save`, editForm.value).then((res) => {
      if (res.code === 200) {
        // ElMessage.success('活动上传成功，请耐心等候管理员审核');
        ElMessageBox.alert('活动上传成功，管理员审核通过后将会显示。', '提示', {
          // if you want to disable its autofocus
          // autofocus: false,
          confirmButtonText: '确定',
          callback: () => {},
        })
        open.value = false;
        getInfo();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

  getInfo()

</script>
  
  <style scoped>
  .article-list-container {
    max-width: 980px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .article-list-card {
    color: #555;
    margin-bottom: 20px;
  }
  
  .list-title {
    font-size: 24px;
    font-weight: normal;
    margin: 0 0 20px 0;
    text-align: center;
    color: #0f95b0;
  }
  
  .article-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .article-item {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .article-item:hover {
    background-color: #f5f5f5;
  }

  .article-item:hover .article-title{
    color: #c35556;
  }
  
  .article-thumbnail {
    width: 140px;
    height: 100px;
    border-radius: 4px;
  }
  
  .article-info {
    flex: 1;
  }
  
  .article-title {
    font-size: 18px;
    margin: 0 0 10px 0;
    color: #666;
    font-weight: normal;
  }
  
  .article-meta {
    font-size: 14px;
    color: #666;
  }
  
  .publish-date {
    font-style: italic;
  }
  .atl-tag, .atl-like{
    margin: 5px 0;
  }
  .atl-like{
    font-size: 13px;
  }
  .atl-like span{
    padding: 0 10px;
  }
  .publish-btn{
    float: right;
    background-color: #d98481;
    color: #fff;
    width: 50px;
    height: 50px;
    text-align: center;
    border-radius: 25px;
    padding-top: 2px;
    cursor: pointer;
    margin-left: 15px;
}
.publish-btn:hover{
    background-color: #e2645f;
}
.publish-btn .el-icon{
    font-size: 20px;
}
.addpic{
font-size: 22px;
padding: 20px 25px 15px 25px;
border: 2px dashed #ccc;
color: #888;
height: 68px;
}
.img-list{
display: flex;
flex-wrap: wrap;
}
.img-list .img-li{
width: 260px;
position: relative;
margin-right: 10px;
}
.logo-remove{
font-size: 22px;
position: absolute;
top: 10px;
right: 10px;
color: #f00;
cursor: pointer;
text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
box-shadow: #fff 3px 5px 6px;
background-color: #fff;
}
.logo-remove:HOVER{
color: #F56C6C;
}
.detail-pics{
  width: 80%;
  margin-top: 30px;
}
.green{
  color: #0f95b0;
}
.search-div{
  margin-bottom: 15px;
}
  </style>